package com.example.design.nioandnettty.practice.聊天室;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class GroupChatClient {
    //属性
    private final String host;
    private final int port;
    public GroupChatClient(String host,int port){
        this.host=host;
        this.port=port;
    }
    public void run() throws InterruptedException {
        EventLoopGroup eventExecutors=new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //得到管道
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //加入相关的handler
                            //向管道添加一个解码器，也是一个ChannelHandler
                            pipeline.addLast("decoder",new StringDecoder());
                            //向管道添加一个编码器，也是一个ChannelHandler
                            pipeline.addLast("encoder",new StringEncoder());
                            //加入自定义的handler
                            pipeline.addLast(new GroupChatClientHandler());
                        }
                    });
            ChannelFuture sync = bootstrap.connect(host, port).sync();
            //得到channel
            Channel channel = sync.channel();
            System.out.println("------"+channel.localAddress()+"-----");
            //客户端需要输入的信息，创建一个扫描器
            Scanner scanner = new Scanner(System.in);
            while(scanner.hasNextLine()){
                String msg = scanner.nextLine();
                //通过channel，发送到服务器端
                channel.writeAndFlush(msg+"\n");
            }
        } finally {
            eventExecutors.shutdownGracefully();
        }
    }
    public static void main(String[] args) throws InterruptedException {
        new GroupChatClient("127.0.0.1",8002).run();
    }
}
